package com.irain.pp.tool;


import com.irain.pp.tool.exception.UtilsInitException;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @author Administrator
 * @date 2017/10/26 19:27
 */
public class Md5Utils {

    private static final char[] HEX_CODE = {'0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    private static final MessageDigest MD5;
    private static final MessageDigest SHA;

    static {
        try {
            MD5 = MessageDigest.getInstance("MD5");
            SHA = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            throw new UtilsInitException(e);
        }
    }

    public static byte[] encodeByMD5(String text){
        try {
            return MD5.digest(text.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            throw new UnsupportedOperationException();
        }
    }

    public static String encode64(String text){
        return Base64.getEncoder().encodeToString(encodeByMD5(text));
    }

    public static String encode32(String text){
        return ByteUtils.toHex(encodeByMD5(text));
    }

    public static String encode16(String text){
        return encode32(text).substring(8,24);
    }

}
